package com.kinon.ceshiaccount.fragment.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.activity.OrderPayActivity;
import com.kinon.ceshiaccount.adapter.DiningTypeAdapter;
import com.kinon.ceshiaccount.adapter.DishesAdapter;
import com.kinon.ceshiaccount.adapter.MenuAdapter;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.CookbooksBean;
import com.kinon.ceshiaccount.bean.RoleBean;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.bean.menu.Breakfast;
import com.kinon.ceshiaccount.bean.menu.SelDisches;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.fragment.BaseFragment;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.MyCallback;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.util.LunchTypeUtil;
import com.kinon.ceshiaccount.util.MyShowDialog;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.util.SoundPoolManage;
import com.kinon.ceshiaccount.util.SysTimeManage;
import com.kinon.ceshiaccount.util.ToastUtil;
import com.kinon.ceshiaccount.view.CustomDialog;


import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;


/**
 * Created by luohao on 2017-06-16.
 * 结算页面，负责金额计算生成结算订单
 */

public class MenuFragment extends BaseFragment implements View.OnClickListener
        ,DishesAdapter.DishesClickListener{
    private View mView;
    private TextView tv_menuType;
    private TextView   btn_clearMenu;
    private GridView gv_menu;
    private ListView lv_dishes;
    private TextView tv_num;
    private TextView tv_totalPrice;
    private TextView tv_seltte;

    /**选择就餐类型*/
    private GridView grid_diningType;
    /**显示就餐类型的布局*/
    private RelativeLayout rl_select;

    private Context context;

    private MenuAdapter mMenuAdapter;
    private ArrayList<Breakfast> menuList;
    private ArrayList <SelDisches> disList;
    private DishesAdapter mDisAdapter;
    private int totalNum=0;
    private double totalPriice=0.0;
    private CookbooksBean cooks=null;

    /*就餐类型相关*/
    private int mType=0;
    private ArrayList<RoleBean> binings=null;
    private DiningTypeAdapter diningAdapter=null;
    private int mIndex=0;
    private long firstTime;
    private int itemWidth=110;

    ToastUtil toastUtil=new ToastUtil();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        mView=inflater.inflate(R.layout.fragement_menu_layout,container,false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        SoundPoolManage.getInstance().soundpPlay(2);
        initView();
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
//            Log.e("lh", "onHiddenChanged: ");
            dataClear();
//            couItemWidth();
//            mMenuAdapter.setmWidth(itemWidth);
            if(binings!=null && diningAdapter!=null){
                int timeArea= (int)((System.currentTimeMillis()-firstTime)/(1000*60*60));
                setDiningType();
                if(timeArea>=2){
                    dialogSelect();
                }
            }
        }else{

        }
    }

    private void initView() {
        context= AccountApplication.getInstance();
        tv_menuType=(TextView) mView.findViewById(R.id.tv_menuType);
        btn_clearMenu=(TextView) mView.findViewById(R.id.btn_clearMenu);
        gv_menu=(GridView) mView.findViewById(R.id.gv_menu);
        lv_dishes=(ListView) mView.findViewById(R.id.lv_dishes);
        tv_num=(TextView) mView.findViewById(R.id.tv_num);
        tv_totalPrice=(TextView) mView.findViewById(R.id.tv_totalPrice);
        tv_seltte=(TextView) mView.findViewById(R.id.tv_seltte);
        grid_diningType= (GridView) mView.findViewById(R.id.grid_diningType);
        rl_select= (RelativeLayout) mView.findViewById(R.id.rl_select);

        couItemWidth();
        menuList=new ArrayList<>();
        disList=new ArrayList<>();
        mDisAdapter=new DishesAdapter(disList,mContext);
        lv_dishes.setAdapter(mDisAdapter);
        mMenuAdapter=new MenuAdapter(menuList,mContext,itemWidth);
        gv_menu.setAdapter(mMenuAdapter);



        getCookbooks();
        addClick();
        showDiningType();
    }

    private void couItemWidth(){
        int menuNum=SPManage.getInstance().getInt("mune_line_num",7);
        gv_menu.setNumColumns(menuNum);
        int menuWidth=AccountApplication.SCREEN_HEIGHT
                /3*2-20-(menuNum-1)*10;
        itemWidth=menuWidth/menuNum;
    }

    private void showDiningType(){
        String roles=SPManage.getInstance().getString("roles");
        if (TextUtils.isEmpty(roles)){
            return;
        }
        Gson gson=new Gson();
        binings=new ArrayList<>();
        try {
            JSONArray array=new JSONArray(roles);
            for(int i=0;i<array.length();i++){
                RoleBean bean=gson.fromJson(array.get(i).toString(),RoleBean.class);
                //显示固定的几种
                if(bean.getId()==0 || bean.getId()==1 ||bean.getId()==3 ) {
                    binings.add(bean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(binings.size()==0){
            rl_select.setVisibility(View.GONE);
            return;
        }
        mType=binings.get(0).getId();
        tv_menuType.setText(LunchTypeUtil.lunchType(mType));
        setShowData();
        if(binings.size()<=1){
            rl_select.setVisibility(View.GONE);
            return;
        }

        grid_diningType.setNumColumns(binings.size());
        diningAdapter=new DiningTypeAdapter(context,binings);
        grid_diningType.setAdapter(diningAdapter);
        setDiningType();
        dialogSelect();
        grid_diningType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mIndex=i;
                mType=binings.get(i).getId();
                tv_menuType.setText(LunchTypeUtil.lunchType(mType));
                dataClear();
                setShowData();
                diningAdapter.selectItem(i);
                diningAdapter.notifyDataSetChanged();
            }
        });
    }

    /**获取默认的刷卡类型*/
    private void setDiningType(){
        int  type= SysTimeManage.getInstage().getOrderType(System.currentTimeMillis());
        for(int i=0;i<binings.size();i++){
            if(binings.get(i).getId()==type){
                mIndex=i;
                mType=type;
                continue;
            }
        }
        setShowData();
        diningAdapter.selectItem(mIndex);
        diningAdapter.notifyDataSetChanged();
        tv_menuType.setText(LunchTypeUtil.lunchType(mType));
    }

    private void dialogSelect(){
        firstTime=System.currentTimeMillis();
        CustomDialog dialog=new CustomDialog(1, getContext(),null, binings,
                mIndex,new CustomDialog.DialogClickListener() {
            @Override
            public void onDialogClick(int btn) {
//                        Log.e("lh", "btn== "+btn );
                mIndex=btn;
                mType=binings.get(btn).getId();
                tv_menuType.setText(LunchTypeUtil.lunchType(mType));
                dataClear();
                setShowData();
                diningAdapter.selectItem(btn);
                diningAdapter.notifyDataSetChanged();
            }
        });
        dialog.show();
    }

    private void addClick(){
        mDisAdapter.setDishesClickListener(this);
        gv_menu.setOnItemClickListener(itemListener);
        tv_seltte.setOnClickListener(this);
        btn_clearMenu.setOnClickListener(this);
    }

    private AdapterView.OnItemClickListener itemListener=new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            int amount=menuList.get(i).getAmount();
            if(amount!=0){
                for(int d=0;d<disList.size();d++) {
                    if (menuList.get(i).getProductid() == disList.get(d).getProductid()) {
                        disList.get(d).setNum(disList.get(d).getNum() + 1);
                        break;
                    }
                }
            }else{
                disList.add(0,new SelDisches(menuList.get(i).getProductid(),
                        menuList.get(i).getName(),menuList.get(i).getPrice(),
                        1,i));
            }
            menuList.get(i).setAmount(amount+1);
            totalNum++;
            totalPriice+=menuList.get(i).getPrice();
            setNumPrice(totalNum,totalPriice);

        }
    };

    private void getCookbooks(){

        Call<String> call=HttpManage.getRequestApi()
                .getCookbooks(SPManage.getInstance().getToken());
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {
             Gson gson=new Gson();
                 cooks=gson.fromJson(data,CookbooksBean.class);
//                Log.e("lh", "size== "+cooks.getCookbooks().size() );
                setShowData();

            }

            @Override
            public void onError(int code, String error) {
                toastUtil.Short(error)
                        .setToastBackground(Color.WHITE,0).show();
//                Toast.makeText(mContext,error+"",
//                        Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void setShowData(){
        menuList.clear();
        if(cooks==null){
           return;
        }

        if(mType==0){
            menuList.addAll(cooks.getCookbooks()
                    .get(LunchTypeUtil.weekIndex()).getBreakfast());
        }else if(mType==1){
            menuList.addAll(cooks.getCookbooks()
                    .get(LunchTypeUtil.weekIndex()).getLunch());
        }else if(mType==3){
            menuList.addAll(cooks.getCookbooks()
                    .get(LunchTypeUtil.weekIndex()).getDinner());
        }
        mMenuAdapter.notifyDataSetChanged();
    }

    @Override
    public void ondishesClick(int position, int type) {
        int num=disList.get(position).getNum();
        numPriceCount(position,type);
        if(type==0){
            if(num>1){
                disList.get(position).setNum(num-1);
            }else{
                disList.remove(position);
            }
        }else{
            disList.get(position).setNum(num+1);
        }
        mDisAdapter.notifyDataSetChanged();
    }

    private void saveProductOrder(){
       if(disList.size()<=0){
           toastUtil.Short("请选择商品")
                   .setToastBackground(Color.WHITE,0).show();
//           Toast.makeText(context,"请选择商品",
//                   Toast.LENGTH_SHORT).show();
           return;
       }
        long nonce_str=System.currentTimeMillis();

        Gson gson=new Gson();
        String strData=gson.toJson(disList);

        if(!Constant.URGENT_TYPE){
            callsaveProductOrder(strData,nonce_str+"");
        }else{
            urgentJiesuan (true,"",nonce_str+"",strData);
        }
        Log.e("lh","strData=="+strData);

    }

    private void callsaveProductOrder(final String strData, final String nonce_str){
        Call<BaseBean<String>> call=HttpManage.getReqLunchApi()
                .saveProductOrder(SPManage.getInstance().getToken()
                        ,mType+"",totalPriice+"",strData,nonce_str);
        MyShowDialog.showLoadingDialog(getActivity(),"结算中");
        call.enqueue(new MyCallback< BaseBean<String>>(){
            @Override
            public void onSuccess(Call<BaseBean<String>> call, Response<BaseBean<String>> response) {
                MyShowDialog.closeLoadingDialog();
                BaseBean<String> base=response.body();
//                Intent intent=new Intent(getActivity(), OrderPayActivity.class);
//                intent.putExtra("total",totalPriice+"");
//                intent.putExtra("diningType",mType);
//                intent.putExtra("oridrid",base.getData());
//                startActivity(intent);
//                dataClear();
                urgentJiesuan(false,base.getData(),nonce_str,"");
            }

            @Override
            public void onError(int code, String error) {
                MyShowDialog.closeLoadingDialog();
                if(code==Constant.ERROR_TIMEOUT_CODE){
                    urgentJiesuan(false,"",nonce_str,strData);
                }else{
                    toastUtil.Short("error")
                            .setToastBackground(Color.WHITE,0).show();
//                    Toast.makeText(context,error,Toast.LENGTH_SHORT).show();
                }

            }
        });
    }


    /**紧急结算 urgent=true紧急模式 */
    private void urgentJiesuan (boolean urgent,String orderid,
                                String nonce_str,String detail){
        Intent intent = new Intent(getContext(), OrderPayActivity.class);
        intent.putExtra("total",totalPriice+"");
        intent.putExtra("diningType",mType);
        intent.putExtra("oridrid",orderid);
        intent.putExtra("urgent",urgent);
        intent.putExtra("nonce_str",nonce_str);
        intent.putExtra("orderDetail",detail);
        startActivity(intent);
        //完成跳转然后清空数据
        dataClear();
    }

    //计算数量和价格
    private void numPriceCount(int position,int count ){

//       int index=disList.get(position).getIndex();
        if(count==0) {
//            menuList.get(index).setAmount(menuList.get(index).getAmount()-1);
            totalNum--;
            totalPriice -= disList.get(position).getPrice();
        }else{
//            menuList.get(index).setAmount(menuList.get(index).getAmount()+1);
            totalNum++;
            totalPriice += disList.get(position).getPrice();
        }

        setNumPrice(totalNum, totalPriice);
    }
    private void setNumPrice(int totalNum,double totalPriice){
        tv_num.setText(totalNum+"");
        tv_totalPrice.setText(totalPriice+"");
        mDisAdapter.notifyDataSetChanged();
//        mMenuAdapter.notifyDataSetChanged();
    }
    /**清空数据*/
    private void dataClear(){
        for(int i=0;i<disList.size();i++){
           menuList.get(disList.get(i).getIndex()).setAmount(0);
        }
        disList.clear();
        totalNum=0;
        totalPriice=0.0;
        setNumPrice(0,0.0);
        mDisAdapter.notifyDataSetChanged();
        mMenuAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_clearMenu:
                dataClear();
            break;
            case R.id.tv_seltte:

                saveProductOrder();
            break;
        }
    }

}
